package myarraylist;

import java.util.Arrays;

public class MyAarrayList implements IList{
    public int[] elem;
    public int usedSize;
    public static final int DEFAULT_SIZE=10;
    public MyAarrayList(){
        this.elem=new int[DEFAULT_SIZE];
    }
    public MyAarrayList(int custom){
        this.elem=new int[custom];
    }
    public boolean isFull(){
        return usedSize==elem.length;
    }
    public void Expansion(){
        if (isFull()){
            elem= Arrays.copyOf(elem,elem.length*2);
        }
    }
    public boolean isEmpty(){
        return this.usedSize==0;
    }
    private void checkPosOnGetAndSet(int pos) throws PosisLegal{
        if(pos < 0 || pos >= usedSize) {
            System.out.println("不符合法！");
            throw new PosisLegal("获取指定下标的元素异常: "+pos);
        }
    }
    @Override
    public void add(int data) {
        //判断数组是否已经存放满了，如果满了就要进行扩容在存放数组
        Expansion();

        elem[usedSize]=data;
        usedSize++;
    }
    public void isLegal(int pos)throws PosisLegal{
        if(pos<0||pos>usedSize){
            throw new PosisLegal("pos位置不合法异常");
        }
    }
    @Override
    public void add(int pos, int data){
        try {
            isLegal(pos);
        }catch (PosisLegal e){
            e.printStackTrace();
        }
        Expansion();
        for (int i = usedSize-1; i >=pos; i--) {
            elem[i+1]=elem[i];
        }
        elem[pos]=data;
        this.usedSize++;
    }

    @Override
    public boolean contains(int toFind){
        for (int i = 0; i < this.usedSize; i++) {
            if(elem[i]==toFind){
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind){
        for (int i = 0; i < usedSize; i++) {
            if(elem[i]==toFind){
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos)throws MyArrayEmpty{
        checkPosOnGetAndSet(pos);
        if(isEmpty()){
            throw new MyArrayEmpty("顺序表为空");
        }
        return elem[pos];
    }

    @Override
    public void set(int pos, int value) {
        checkPosOnGetAndSet(pos);

        elem[pos]=value;
    }

    @Override
    public void remove(int toRemove) {
        int index=indexOf(toRemove);
        if(index==-1){
            System.out.println("没找到这个元素");
            return;
        }
        for (int i = index; i < usedSize-1; i++) {
            elem[i]=elem[i+1];
        }
        usedSize--;
    }

    @Override
    public int size() {
        return this.usedSize;
    }

    @Override
    public void clear() {
        this.usedSize=0;
    }

    @Override
    public void display() {
        for (int i = 0; i < usedSize; i++) {
            System.out.print(elem[i]+" ");
        }
        System.out.println();
    }
}
